<template>
  <div ref="wrapper">
    <slot></slot>
  </div>
</template>

<script>
import BScroll from "better-scroll";
export default {
  props: {
    probeType: {
      type: Number,
      default: 1,
    },
    click: {
      type: Boolean,
      default: true,
    },
    data: {
      type: Array,
      default: null,
    },
    scrollX: {
      type: Boolean,
      default: false,
    },
    // 是否监听滚动事件
    ListenScroll: {
      type: Boolean,
      default: false,
    },
    // 是否开启上拉刷新
    pullup: {
      type: Boolean,
      default: false,
    },
    beforeScroll: {
      type: Boolean,
      default: false,
    },
    refreshDelay: {
      type: Number,
      default: 20,
    },
    bounce: {
      type: Boolean,
      default: true,
    },
    momentum: {
      type: Boolean,
      default: true,
    },
    scrollbar: {
      type: Boolean,
      default: false,
    },
    stopPropagation: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    setTimeout(() => {
      this._initScroll();
    }, 20);
  },
  methods: {
    _initScroll() {
      if (!this.$refs.wrapper) {
        return;
      }
      this.scroll = new BScroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click,
        scrollX: this.scrollX,
        scrollY: !this.scrollX,
        eventPassthrough: this.scrollX ? "vertical" : "horizontal",
        bounce: this.bounce,
        bounceTime: this.scrollX ? 0 : 700,
        scrollbar: this.scrollbar,
        stopPropagation: this.stopPropagation,
        useTransition: false,
      });
      if (this.ListenScroll) {
        let _this = this;
        this.scroll.on("scroll", (pos) => {
          _this.$emit("scroll", pos);
        });
      }
      if (this.pullup) {
        if (!this.scrollX) {
          this.scroll.on("scrollEnd", () => {
            if (this.scroll.y <= this.scroll.maxScrollY + 50) {
              // 滚动到y轴底部了
              this.$emit("scrollToEnd");
            }
          });
        } else {
          this.scroll.on("scrollEnd", () => {
            if (this.scroll.x <= this.scroll.maxScrollX + 50) {
              console.log(this.scroll.maxScrollX);

              // 滚动到x轴底部了
              this.$emit("scrollToEndX");
            }
          });
        }
      }

      if (this.beforeScroll) {
        this.scroll.on("beforeScrollStart", () => {
          this.$emit("beforeScroll");
        });
      }
    },
    enable() {
      this.scroll && this.scroll.enable();
    },
    disable() {
      this.scroll && this.scroll.disable();
    },
    refresh() {
      this.scroll && this.scroll.refresh();
    },
    scrollTo() {
      this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments);
    },
    scrollToElement() {
      this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments);
    },
  },
  watch: {
    data() {
      setTimeout(() => {
        this.refresh();
      }, this.refreshDelay);
    },
  },
};
</script>

